/***************************************************************************************
* Copyright (c) 2014-2022 Zihao Yu, Nanjing University
*
* NEMU is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*          http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
*
* See the Mulan PSL v2 for more details.
***************************************************************************************/

#include <isa.h>
#include <cpu/cpu.h>
#include <readline/readline.h>
#include <readline/history.h>
#include <stdint.h>
#include "common.h"
#include "memory/paddr.h"
#include "sdb.h"
#include "utils.h"

static int is_batch_mode = false;

void init_regex();
void init_wp_pool();

/* We use the `readline' library to provide more flexibility to read from stdin. */
static char* rl_gets() {
  static char *line_read = NULL;

  if (line_read) {
    free(line_read);
    line_read = NULL;
  }

  line_read = readline("(nemu) ");

  if (line_read && *line_read) {
    add_history(line_read);
  }

  return line_read;
}

static int cmd_c(char *args) {
  cpu_exec(-1);
  return 0;
}


static int cmd_q(char *args) {
  if (nemu_state.state == NEMU_STOP) nemu_state.state = NEMU_QUIT;
  return -1;
}

static int cmd_help(char *args);
static int cmd_si(char *args);
static int cmd_info(char *args);
static int cmd_x(char *args);
static int cmd_p(char *args);
static int cmd_w(char *args);
static int cmd_d(char *args);

static struct {
  const char *name;
  const char *description;
  int (*handler) (char *);
} cmd_table [] = {
  { "help", "Display information about all supported commands", cmd_help },
  { "c", "Continue the execution of the program", cmd_c },
  { "q", "Exit NEMU", cmd_q },
  { "si", "Pause program execution after executing [N] instructions in one step", cmd_si },
  { "info", "Print program status, subcmd r for registers status and subcmd w for watchpoint information", cmd_info },
  { "x", "Scan memory(Word)", cmd_x },
  { "p", "Expression evaluation", cmd_p },
  { "w", "Set watchpoint", cmd_w },
  { "d", "Delete watchpoint", cmd_d },

};

#define NR_CMD ARRLEN(cmd_table)

static int cmd_help(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");
  int i;

  if (arg == NULL) {
    /* no argument given */
    for (i = 0; i < NR_CMD; i ++) {
      printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
    }
  }
  else {
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(arg, cmd_table[i].name) == 0) {
        printf("%s - %s\n", cmd_table[i].name, cmd_table[i].description);
        return 0;
      }
    }
    printf("Unknown command '%s'\n", arg);
  }
  return 0;
}

static int cmd_si(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");

  if (arg == NULL) {
    /* no argument given */
	cpu_exec(1);
  }
  else {
	int len = strlen(arg);
	int n = 0;

	/* convert string to number */
	for (int i = 0; i < len; i++) {
	  if (arg[i] >= '0' && arg[i] <= '9')
	  	n = n*10 + arg[i] - '0';
	  else {
		printf("Invalid number.\n");
		return 0;
	  }
	}

    cpu_exec(n);
  }

  return 0;
}

static int cmd_info(char *args) {
  /* extract the first argument */
  char *arg = strtok(NULL, " ");

  if (arg == NULL) {
    /* no argument given */
	printf("Please give a argument(r/w).\n");
	return 0;
  }
  else {
	if (strcmp(arg, "r") == 0) isa_reg_display();
	else if (strcmp(arg, "w") == 0) watchpoint_display();
	else printf("Invalid argument.\n");
  }

  return 0;
}

static int cmd_x(char *args) {
  /* extract two arguments */
  char *arg1 = strtok(NULL, " ");
  char *arg2 = arg1 + strlen(arg1) + 1;

  if (arg1 == NULL || arg2 == NULL) {
    /* no (enough) argument given */
	printf("Argument(s) needed.\n");
	return 0;
  }
  else {
	/* convert arg1 to number */
	int len1 = strlen(arg1);
	int N = 0;
	
	for (int i = 0; i < len1; i++) {
	  if (arg1[i] >= '0' && arg1[i] <= '9')
	  	N = N*10 + arg1[i] - '0';
	  else {
		printf("Invalid first argument.\n");
		return 0;
	  }
	}

	/* calculate value of arg2 */
	bool success = true;
	word_t expr_val = expr(arg2, &success);
	if(!success) {
      printf("Expression is wrong.\n");
	  return 0;
	}

	if (expr_val < 0x80000000) {
	  printf("Invalid address.\n");
	  return 0;
	}

	uint8_t* addr;
	uint32_t paddr = expr_val;
	for (int i = 0; i < N; i++) {
	  addr = guest_to_host(paddr);

	  printf("0x%8x:    0x%08x\n", paddr, *((uint32_t *)addr));

	  paddr += 4;
	}
  }

  return 0;
}

static int cmd_p(char *args) {
  if (args == NULL) {
    /* no expression given */
	printf("No expression.\n");
	return 0;
  }
  else {
	bool success = true;
	word_t val = expr(args, &success);
	if(success) {
	  printf("%s = %u\n", args, val);
	}
	else {
      printf("Expression is wrong.\n");
	}
  }

  return 0;
}

static int cmd_w(char *args) {
  if (args == NULL) {
    /* no expression given */
	printf("No expression.\n");
	return 0;
  }
  else {
    new_wp(args);
  }

  return 0;
}

static int cmd_d(char *args) {
  if (args == NULL) {
    /* no expression given */
	printf("No expression.\n");
	return 0;
  }
  else {
	int N = -1;
    sscanf(args, "%d", &N);

	free_wp(N);
  }

  return 0;
}

void sdb_set_batch_mode() {
  is_batch_mode = true;
}

void sdb_mainloop() {
  if (is_batch_mode) {
    cmd_c(NULL);
    return;
  }

  for (char *str; (str = rl_gets()) != NULL; ) {
    char *str_end = str + strlen(str);

    /* extract the first token as the command */
    char *cmd = strtok(str, " ");
    if (cmd == NULL) { continue; }

    /* treat the remaining string as the arguments,
     * which may need further parsing
     */
    char *args = cmd + strlen(cmd) + 1;
    if (args >= str_end) {
      args = NULL;
    }

#ifdef CONFIG_DEVICE
    extern void sdl_clear_event_queue();
    sdl_clear_event_queue();
#endif

    int i;
    for (i = 0; i < NR_CMD; i ++) {
      if (strcmp(cmd, cmd_table[i].name) == 0) {
        if (cmd_table[i].handler(args) < 0) { return; }
        break;
      }
    }

    if (i == NR_CMD) { printf("Unknown command '%s'\n", cmd); }
  }
}

void init_sdb() {
  /* Compile the regular expressions. */
  init_regex();

  /* Initialize the watchpoint pool. */
  init_wp_pool();
}
